package com.cnswhy.cloud.server.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.cnswhy.cloud.common.core.base.entity.SuperEntity;
import com.cnswhy.cloud.common.core.entity.SystemUserSaveDTO;
import com.cnswhy.cloud.common.core.entity.constant.CnswhyConstant;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.BizAssert;
import com.cnswhy.cloud.common.core.utils.Md5Utils;
import com.cnswhy.cloud.server.system.dto.*;
import com.cnswhy.cloud.server.system.entity.SystemRole;
import com.cnswhy.cloud.server.system.entity.SystemUser;
import com.cnswhy.cloud.server.system.entity.UserRole;
import com.cnswhy.cloud.server.system.service.SystemRoleService;
import com.cnswhy.cloud.server.system.service.SystemUserService;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.server.system.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
//import com.github.zuihou.security.annotation.PreAuth;

import javax.annotation.Resource;


/**
 * <p>
 * 前端控制器
 * 用户表
 * </p>
 *
 * @author cnswhy
 * @date 2020-10-24
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/systemUser")
@Api(value = "SystemUser", tags = "用户表")
//@PreAuth(replace = "systemUser:")
public class SystemUserController extends SuperController<SystemUserService, Long, SystemUser, SystemUserPageDTO, SystemUserSaveDTO, SystemUserUpdateDTO> {
    @Resource
    PasswordEncoder passwordEncoder;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    SystemRoleService systemRoleService;
    //@RequestMapping(value = "/saveMerchant", method = RequestMethod.POST)
    @PostMapping(value = "/saveMerchant")
    @Transactional
    //@SysLog(value = "新增", request = false)
    //@PreAuth("hasPermit('{}add')")
    public R<SystemUser> saveMerchant(@RequestParam("userName") String userName,@RequestParam("password") String password,@RequestParam("merchantId") Long merchantId) {
        SystemUserSaveDTO systemUserSaveDTO = new SystemUserSaveDTO();
        systemUserSaveDTO.setUsername(userName);
        systemUserSaveDTO.setPassword(password);
        systemUserSaveDTO.setMerchantId(merchantId);
        R<SystemUser> result = handlerSave(systemUserSaveDTO);
        if (result.getDefExec()) {
            SystemUser model = BeanUtil.toBean(systemUserSaveDTO, getEntityClass());
            getBaseService().save(model);
            result  = handlerAfterSave( systemUserSaveDTO,model);
            SystemRole systemRole = systemRoleService.getOne(Wraps.<SystemRole>lbQ().eq(SystemRole::getCode,"PT_MERCH"));
            UserRole userRole = new UserRole();
            userRole.setUserId(model.getId());
            userRole.setRoleId(systemRole.getId());
            userRoleService.save(userRole);
            if(result.getDefExec()){
                result.setData(model);
            }
        }

        return result;
    }
    /*public R<SystemUser> saveMerchant(@RequestBody @Validated SystemUserSaveDTO systemUserSaveDTO) {
        R<SystemUser> result = handlerSave(systemUserSaveDTO);
        if (result.getDefExec()) {
            SystemUser model = BeanUtil.toBean(systemUserSaveDTO, getEntityClass());
            getBaseService().save(model);
            result  = handlerAfterSave( systemUserSaveDTO,model);
            SystemRole systemRole = systemRoleService.getOne(Wraps.<SystemRole>lbQ().eq(SystemRole::getCode,"PT_MERCH"));
            UserRole userRole = new UserRole();
            userRole.setUserId(model.getId());
            userRole.setRoleId(systemRole.getId());
            userRoleService.save(userRole);
            if(result.getDefExec()){
                result.setData(model);
            }
        }

        return result;
    }*/
    @Override
    public R<SystemUser> handlerSave(SystemUserSaveDTO systemUserSaveDTO) {
        systemUserSaveDTO.setDeptId(0L);
        systemUserSaveDTO.setStatus("1");
        systemUserSaveDTO.setAvatar("BiazfanxmamNRoxxVxka.png");
        systemUserSaveDTO.setPassword(passwordEncoder.encode(Md5Utils.getMd5(CnswhyConstant.DEFAULT_PASSWORD)));
        return R.successDef();
    }

    @Override
    public R<Boolean> handlerDelete(List<Long> longs) {
        for(Long id : longs){
            userRoleService.remove(Wraps.<UserRole>lbQ().eq(UserRole::getUserId,id));
        }
        return R.successDef();
    }

    /**
     * 查询用户的角色
     *
     * @param userId 角色id
     * @return 新增结果
     */
    @ApiOperation(value = "查询用户的角色", notes = "查询用户的角色")
    @GetMapping("/role/{userId}")
    //@SysLog("查询角色的用户")
    public R<List<Long>> findRoleByUserId(@PathVariable Long userId) {
        List<UserRole> list = userRoleService.list(Wraps.<UserRole>lbQ().eq(UserRole::getUserId, userId));
        return success(list.stream().mapToLong(UserRole::getRoleId).boxed().collect(Collectors.toList()));
    }
    @ApiOperation(value = "修改用户的角色", notes = "修改用户的角色")
    @PostMapping("/updateRole")
    //@SysLog("查询角色的用户")
    public R<Boolean> updateRolesByUserId(@RequestBody SystemUserRoleSaveDTO systemUserRoleSaveDTO) {
        log.info(JSON.toJSONString(systemUserRoleSaveDTO));
        userRoleService.remove(Wraps.<UserRole>lbQ().eq(UserRole::getUserId, systemUserRoleSaveDTO.getUserId()));
        for(Long id : systemUserRoleSaveDTO.getRoleIdList()){
            UserRole userRole = new UserRole();
            userRole.setUserId(systemUserRoleSaveDTO.getUserId());
            userRole.setRoleId(id);
            userRoleService.save(userRole);
        }
        return success();
    }
    /**
     * 重置密码
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "重置密码", notes = "重置密码")
    @PostMapping("/reset")
    //@SysLog("'重置密码:' + #data.id")
    public R<Boolean> reset(@RequestBody @Validated(SuperEntity.Update.class) UserUpdatePasswordDTO data) {
        SystemUser systemUser = baseService.getById(data.getId());
        BizAssert.equals(data.getConfirmPassword(), data.getPassword(), "2次输入的密码不一致");
        systemUser.setPassword(passwordEncoder.encode(Md5Utils.getMd5(data.getPassword())));
        baseService.updateById(systemUser);
        return success();
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<SystemUser> systemUserList = list.stream().map((map) -> {
            SystemUser systemUser = SystemUser.builder().build();
            return systemUser;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(systemUserList));
    }
}
